package com.lyc.dao.impl;

import com.lyc.bean.Courier;
import com.lyc.bean.User;
import com.lyc.dao.BaseUserDao;
import com.lyc.util.DateFormatUtil;
import com.lyc.util.DruidUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BaseUserDaoImpl implements BaseUserDao {

    // 用于查询数据库中的用户人数
    public static final String SQL_CONSOLE = "SELECT COUNT(ID) data_1size, COUNT(TO_DAYS(REGISTERTIME)=TO_DAYS(NOW()) OR NULL) data_1day FROM USER";
    // 用于查询数据库中的所有用户信息
    public static final String SQL_FIND_ALL = "SELECT * FROM USER";
    // 用于分页查询数据库中的用户信息
    public static final String SQL_FIND_LIMIT = "SELECT * FROM USER LIMIT ?,?";
    // 通过快递员手机号查询用户信息
    public static final String SQL_FIND_BY_USERPHONE = "SELECT * FROM USER WHERE USERPHONE=?";
    // 录入用户
    public static final String SQL_INSERT = "INSERT INTO USER (USERNAME,USERPHONE,IDNUMBER,PASSWORD,REGISTERTIME) VALUES(?,?,?,?,NOW())";
    // 用户修改
    public static final String SQL_UPDATE = "UPDATE USER SET USERNAME=?,IDNUMBER=?,PASSWORD=? WHERE USERPHONE=?";
    // 用户的删除
    public static final String SQL_DELETE = "DELETE FROM USER WHERE USERPHONE=?";

    /**
     * 用于查询数据库中用户的个数
     * @return list.size()
     */
    @Override
    public List<Map<String, Integer>> console() {
        ArrayList<Map<String,Integer>> data = new ArrayList<>();
        // 1.获取数据库的连接
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        // 2.预编译SQL语句
        try {
            state = conn.prepareStatement(SQL_CONSOLE);
            // 3.填充参数（可选）
            // 4.执行SQL语句
            result = state.executeQuery();
            // 5.获取执行的结果
            if (result.next()){
                int data_1size = result.getInt("data_1size");
                int data_1day = result.getInt("data_1day");
                Map data1 = new HashMap();
                data1.put("data_1size", data_1size);
                data1.put("data_1day", data_1day);
                data.add(data1);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            // 6.资源的释放
            DruidUtil.close(conn, state, result);
        }
        return data;
    }

    /**
     * 用于查询所有用户
     * @param limit      是否分页的标记，true表示分页，false表示查询所有快递员
     * @param offset     SQL语句的起始索引
     * @param pageNumber 页查询的数量
     * @return 用户的集合
     */
    @Override
    public List<User> findAll(boolean limit, int offset, int pageNumber) {
        ArrayList<User> data = new ArrayList<>();
        // 1.获取数据库的连接
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        // 2.预编译SQL语句
        try {
            if (limit) {
                state = conn.prepareStatement(SQL_FIND_LIMIT);
                // 3.填充参数（可选）
                state.setInt(1, offset);
                state.setInt(2, pageNumber);

            }else {
                state = conn.prepareStatement(SQL_FIND_ALL);
            }
            // 4.执行SQL语句
            result = state.executeQuery();
            // 5.获取执行的结果
            while (result.next()){
                int id = result.getInt("id");
                String username = result.getString("username");
                String userPhone = result.getString("userPhone");
                String idNumber = result.getString("idNumber");
                String password = result.getString("password");
                Timestamp registerTime = result.getTimestamp("registerTime");
                Timestamp loginTime = result.getTimestamp("loginTime");
                User u = new User(id, username, userPhone, idNumber, password, registerTime, loginTime);
                data.add(u);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            // 6.资源的释放
            DruidUtil.close(conn, state, result);
        }
        return data;
    }

    /**
     * 根据手机号码查询用户信息
     * @param userPhone 手机号码
     * @return 查询的用户信息，手机号不存在时返回null
     */
    @Override
    public User findByUserPhone(String userPhone) {
        // 1.获取数据库的连接
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        // 2.预编译SQL语句
        try {
            state = conn.prepareStatement(SQL_FIND_BY_USERPHONE);
            // 3.填充参数(可选)
            state.setString(1, userPhone);
            // 4.执行SQL语句
            result = state.executeQuery();
            // 5.获取执行的结果
            while (result.next()){
                int id = result.getInt("id");
                String username = result.getString("username");
                String idNumber = result.getString("idNumber");
                String password = result.getString("password");
                Timestamp registerTime = result.getTimestamp("registerTime");
                Timestamp loginTime = result.getTimestamp("loginTime");
                User u = new User(id, username, userPhone, idNumber, password, registerTime, loginTime);
                return u;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            // 6.资源的释放
            DruidUtil.close(conn, state, result);
        }
        return null;
    }

    /**
     * 用户的录入
     * @param u 要录入的用户对象
     * @return 录入的结果，true表示录入成功，false表示录入失败
     */
    @Override
    public boolean insert(User u) {
        // 1.连接的获取
        Connection conn = DruidUtil.getConnection();
        // 2.预编译SQL语句
        PreparedStatement state = null;
        try {
            state = conn.prepareStatement(SQL_INSERT);
            // 3.填充参数
            state.setString(1, u.getUsername());
            state.setString(2, u.getUserPhone());
            state.setString(3, u.getIdNumber());
            state.setString(4, u.getPassword());
            // 4.执行SQL语句,并获取执行结果
            return state.executeUpdate() > 0 ? true : false;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            // 5.释放资源
            DruidUtil.close(conn, state, null);
        }
        return false;
    }

    /**
     * 用户的修改
     * @param userPhone 要修改的用户手机号
     * @param newUser   新修改的用户对象(username, userPhone, idNumber, password)
     * @return 修改的结果，true表示录入成功，false表示录入失败
     */
    @Override
    public boolean update(String userPhone, User newUser) {
        // 1.连接的获取
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        // 2.预编译SQL语句
        try {
            state = conn.prepareStatement(SQL_UPDATE);
            state.setString(1, newUser.getUsername());
            state.setString(2, newUser.getIdNumber());
            state.setString(3, newUser.getPassword());
            state.setString(4, userPhone);
            return state.executeUpdate() > 0 ? true : false;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn, state,null);
        }
        return false;
    }

    /**
     * 根据手机号删除单个用户信息
     * @param userPhone 要删除的快递员手机号
     * @return 删除的结果，true表示删除成功，false表示删除失败
     */
    @Override
    public boolean delete(String userPhone) {
        // 1.连接的获取
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        // 2.预编译SQL语句
        try {
            state = conn.prepareStatement(SQL_DELETE);
            state.setString(1, userPhone);
            return state.executeUpdate() > 0 ? true : false;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn, state,null);
        }
        return false;
    }
}
